package com.xiaobai.design_pattern.proxy;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author wangtw
 * @date 2023/12/3 20:17
 * @description
 */
public class CglibGamePlayerProxy implements MethodInterceptor {

    private Object targetObject;

    public CglibGamePlayerProxy(Object targetObject) {
        this.targetObject = targetObject;
    }

    private void start() {
        System.out.println("开始时间为" + new Date());
    }

    private void end() {
        System.out.println("结束时间为" + new Date());
    }

    /**
     * 获取角色名称
     * @param operateStep
     */
    private void operatePerson(String operateStep) {
        Class<?> aClass = this.targetObject.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.getName().equals("name")) {
                declaredField.setAccessible(true);
                try {
                    Object name = declaredField.get(this.targetObject);
                    System.out.println(name + operateStep + "操作");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("============开始执行" + method.getName() + "方法==============");
        operatePerson("开始");
        start();
        Object result = methodProxy.invoke(this.targetObject, objects);
        operatePerson("结束");
        end();
        System.out.println("============结束执行" + method.getName() + "方法==============");
        return result;
    }
}
